package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage iPage = userInfoApi.findAll(page, pagesize);
        return new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
    }

    public UserInfo findUserById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        if(redisTemplate.hasKey(Constants.FREEZE_USER+info.getId())) {
            info.setUserStatus("2");
        }
        return info;
    }

    //查询指定用户发布的所有视频列表
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    //查询动态
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1、调用API查询数据 ：Movment对象
        PageResult result = movementApi.findByUserId(uid,state,page,pagesize);
        //2、解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、一个Movment对象转化为一个Vo
        if(CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if(userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }
        //4、构造返回值
        result.setItems(vos);
        return result;
    }

    //用户冻结
    public Map userFreeze(Map params) {
        String freezingTimeStr = (String) params.get("freezingTime");
        int freezingTime = Integer.parseInt(freezingTimeStr);
        Integer userId = (Integer) params.get("userId");
        int days = 0;
        if (freezingTime == 1) {
            days = 3;
        }
        if (freezingTime == 2) {
            days = 7;
        }
        if (freezingTime == 3) {
            days = -1;
        }
        String value = JSON.toJSONString(params);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER+userId,value,days, TimeUnit.MINUTES);
        Map map = new HashMap();
        map.put("message","冻结成功");
        return map;
    }

    //用户解冻
    public Map userUnfreeze(Map params) {
        Integer userId = (Integer) params.get("userId");
        redisTemplate.delete(Constants.FREEZE_USER + userId);
        Map map = new HashMap();
        map.put("message", "解冻成功");
        return map;
    }

    public ResponseEntity userpass(List<String> list) {
        //遍历存放动态Id的集合，获得需要放行的动态Id
        for (String passMovementId : list) {
            //根据动态id查询动态详情
            Movement movement = movementApi.findById(passMovementId);
            //判断动态详情不为空且动态状态是否为为待审核
            if (movement != null) {
                //更新动态审核状态为拒绝
                movement.setState(1);
            }
            //调用Api根据需要passMovementId更新动态审核状态
            movementApi.passMovements(passMovementId, movement.getState());
        }
        return ResponseEntity.status(200).body("审核通过");
    }
    public ResponseEntity userreject(List<String> list) {
        //遍历存放动态Id的集合，获得需要放行的动态Id
        for (String passMovementId : list) {
            //根据动态id查询动态详情
            Movement movement = movementApi.findById(passMovementId);
            //判断动态详情不为空且动态状态是否为为待审核
            if (movement != null) {
                //更新动态审核状态为拒绝
                movement.setState(2);
            }
            //调用Api根据需要passMovementId更新动态审核状态
            movementApi.passMovements(passMovementId, movement.getState());
        }
        return ResponseEntity.status(200).body("审核拒绝");

    }

    // 查询评论
    public PageResult findComments(Integer page, Integer pagesize, String messageID) {
        List<Comment> comments = commentApi.findComments(messageID, CommentType.COMMENT, page, pagesize);
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }

        ArrayList<CommentVo> vos = new ArrayList<>();
        for (Comment comment : comments) {
            if (comment==null){
                continue;
            }
            Long userId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0,vos);
    }

    //动态详情
    public MovementsVo findMovementById(String userId) {
        Movement movements = movementApi.findById(userId);
        if(movements == null) {
            return null;
        }else {
            UserInfo userInfo = userInfoApi.findById(movements.getUserId());
            return MovementsVo.init(userInfo,movements);
        }
    }
    //置顶
    public String selectTop(String id){
        Movement movement=new Movement();
        movement.setIsTop(id);
        return id;
    }
    //取消置顶
    public String selectnotTop(String id){
        Movement movement=new Movement();
        movement.setNotTop(id);
        return id;
    }
}